package fw.helpers;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gargoylesoftware.htmlunit.ElementNotFoundException;

import fw.ApplicationManager;

public class ChainFinder {
	ApplicationManager app;
	private WebElement chainedElement;
	private List<WebElement> chainedElements;
	private static Logger LOG = LoggerFactory.getLogger(ChainFinder.class);

	public ChainFinder(ApplicationManager app) {
		this.app = app;
		chainedElement = app.getDriver().findElement(By.xpath("./html"));
	}

	public ChainFinder elementLocated(By locator) {
		LOG.debug("Looking for element " + locator + "located");
		try {
			app.wait.until(ExpectedConditions.presenceOfElementLocated(locator));
			chainedElement = chainedElement.findElement(locator);
		} catch (ElementNotFoundException e) {
			e.printStackTrace();
		}
		return this;
	}

	public ChainFinder elementsLocated(By locator) {
		LOG.debug("Looking for elements " + locator + "located");
		try {
			app.wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(locator));
			chainedElements = chainedElement.findElements(locator);
		} catch (ElementNotFoundException e) {
			e.printStackTrace();
		}
		return this;
	}

	public ChainFinder elementVisible(By locator) {
		LOG.debug("Looking for element " + locator + "visible");
		try {
			app.wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
			chainedElement = chainedElement.findElement(locator);
		} catch (ElementNotFoundException e) {
			e.printStackTrace();
		}
		return this;
	}

	public ChainFinder elementClickable(By locator) {
		LOG.debug("Looking for element " + locator + "clickable");
		try {
			app.wait.until(ExpectedConditions.elementToBeClickable(locator));
			chainedElement = chainedElement.findElement(locator);
		} catch (ElementNotFoundException e) {
			e.printStackTrace();
		}
		return this;
	}

	public WebElement getElement() {
		return chainedElement;
	}

	public List<WebElement> getElements() {
		return chainedElements;
	}
}
